package com.wqy.netty;

import com.wqy.netty.model.Request;
import com.wqy.netty.model.Response;
import com.wqy.netty.model.StateCode;
import com.wqy.netty.module.fuben.request.FightRequest;
import com.wqy.netty.module.fuben.response.FightResponse;
import org.jboss.netty.channel.*;

/**
 * @Auther: WangQingyang
 * @Date: 2020/3/30 11:42
 * @Description:
 */
public class HelloHandler extends SimpleChannelHandler {
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        Request message = (Request) e.getMessage();
        System.out.println("收到了："+message);
        if (message.getModule() == 1){
            if (message.getCmd() ==1){
                FightRequest fightRequest = new FightRequest();
                fightRequest.readFromBytes(message.getData());
                System.out.println(fightRequest);

                FightResponse fightResponse = new FightResponse();
                fightResponse.setGold(9999);
                Response response = new Response();
                response.setStateCode(StateCode.SUCCESS);
                response.setCmd((short) 1);
                response.setModule((short) 1);
                response.setData(fightResponse.getBytes());
                ctx.getChannel().write(response);
            }else if(message.getCmd() ==2){

            }
        }else if(message.getModule() == 2){

        }

        super.messageReceived(ctx, e);
    }

    /**
     * 处理消息出现异常
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        System.out.println("exceptionCaught");

        super.exceptionCaught(ctx, e);
    }

    /**
     * 新连接
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelConnected");

        super.channelConnected(ctx, e);
    }

    /**
     * 必须要建立连接，关闭通道时候才会触发
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelDisconnected");

        super.channelDisconnected(ctx, e);
    }

    /**
     * channel 关闭的时候触发
     * @param ctx
     * @param e
     * @throws Exception
     */
    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        System.out.println("channelClosed");

        super.channelClosed(ctx, e);
    }
}
